function sendMessage(action, data) {
  chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, { action, data }, (res) => {
      console.log("bg=>content", res);
      if(action == 'init'){
        document.getElementById("msg").innerHTML = "插件已开启";
      }
    });
  });
}
window.onload = function(){
  sendMessage("init", null);
  chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    if(request.action == 'send-api'){
      document.getElementById("msg").innerHTML = JSON.stringify(request);
      sendRequest(request.params);
      sendResponse();
    }
    sendResponse();
  });
}
function sendRequest(params) {
  var XHR = new XMLHttpRequest();
  const url = "http://172.16.99.131:9998/print/";
  // XHR.timeout = 2000;
  XHR.open("POST", url);
  XHR.setRequestHeader("content-type", "application/json");
  XHR.send(JSON.stringify(params));
  XHR.onreadystatechange = function () {
    // console.log(XHR.responseText)
    if (XHR.readyState == 4 && XHR.status == 200) {
      params.code = 1;
      sendMessage("api", { response : XHR.responseText, params });
      document.getElementById("msg").innerHTML = "success";
    } else {
      params.code = 0;
      // sendMessage("api", { response : XHR.responseText, params });
      document.getElementById("msg").innerHTML = "fail";
    }
  }
}
